package com.addzero.kmp.processor

import com.google.devtools.ksp.processing.*
import com.google.devtools.ksp.symbol.*
import com.google.devtools.ksp.validate
import com.lt.lazy_people_http.annotations.LazyPeopleHttpService
import com.addzero.kmp.util.lowerFirst

class ServiceProviderProcessor(
    private val codeGenerator: CodeGenerator,
    private val logger: KSPLogger,
    private val options: Map<String, String>
) : SymbolProcessor {

    override fun process(resolver: Resolver): List<KSAnnotated> {
        val symbols = resolver.getSymbolsWithAnnotation(LazyPeopleHttpService::class.qualifiedName!!)
        val services = symbols.filterIsInstance<KSClassDeclaration>()
            .filter { it.validate() }
            .toList()

        if (services.isEmpty()) return emptyList()

        // 收集所有源文件的依赖
        val dependencies = services.map { it.containingFile!! }.toSet()

        val file = codeGenerator.createNewFile(
            dependencies = Dependencies(true, *dependencies.toTypedArray()),
            packageName = "com.addzero.kmp.service",
            fileName = "ServiceProvider"
        )

        file.appendText("""
            package com.addzero.kmp.service

            import com.addzero.kmp.core.network.AddHttpClient.hfconfig
            import com.lt.lazy_people_http.annotations.LazyPeopleHttpService

            /**
             * 服务实例提供
             * 由KSP自动生成
             */
            object ServiceProvider {
                ${services.joinToString("\n    ") { service ->
                    "val ${service.simpleName.asString().lowerFirst()}: ${service.qualifiedName!!.asString()} = ${service.qualifiedName!!.asString()}::class.createService(hfconfig)"
                }}
            }
        """.trimIndent())

        return emptyList()
    }
}

class ServiceProviderProcessorProvider : SymbolProcessorProvider {
    override fun create(
        environment: SymbolProcessorEnvironment
    ): SymbolProcessor {
        return ServiceProviderProcessor(
            environment.codeGenerator,
            environment.logger,
            environment.options
        )
    }
} 